<template>
  <div class="borrow-list">
    <!-- 搜索栏 -->
    <div class="search-bar">
      <el-form :model="searchForm" class="search-form">
        <div class="search-item">
          <el-input
            v-model="searchForm.keyword"
            placeholder="搜索用户名、图书名称"
            clearable
            @keyup.enter="handleSearch"
          >
            <template #prefix>
              <el-icon><Search /></el-icon>
            </template>
          </el-input>
        </div>
        
        <div class="search-item">
          <el-select
            v-model="searchForm.status"
            placeholder="借阅状态"
            clearable
          >
            <el-option label="借阅中" value="BORROWED" />
            <el-option label="已归还" value="RETURNED" />
            <el-option label="已逾期" value="OVERDUE" />
          </el-select>
        </div>
        
        <div class="search-item">
          <el-date-picker
            v-model="searchForm.dateRange"
            type="daterange"
            range-separator="至"
            start-placeholder="开始日期"
            end-placeholder="结束日期"
            format="YYYY-MM-DD"
            value-format="YYYY-MM-DD"
          />
        </div>
        
        <div class="search-actions">
          <el-button type="primary" @click="handleSearch">
            <el-icon><Search /></el-icon>
            搜索
          </el-button>
          <el-button @click="handleReset">
            <el-icon><Refresh /></el-icon>
            重置
          </el-button>
        </div>
      </el-form>
    </div>
    
    <!-- 统计卡片 -->
    <div class="stats-row">
      <div class="stat-card">
        <div class="stat-value">{{ stats.totalBorrows || 0 }}</div>
        <div class="stat-label">总借阅数</div>
      </div>
      <div class="stat-card">
        <div class="stat-value">{{ stats.activeBorrows || 0 }}</div>
        <div class="stat-label">借阅中</div>
      </div>
      <div class="stat-card">
        <div class="stat-value">{{ stats.overdueBorrows || 0 }}</div>
        <div class="stat-label">已逾期</div>
      </div>
      <div class="stat-card">
        <div class="stat-value">{{ stats.returnedBorrows || 0 }}</div>
        <div class="stat-label">已归还</div>
      </div>
    </div>
    
    <!-- 表格 -->
    <div class="table-container">
      <div class="table-header">
        <div class="table-title">借阅记录</div>
        <div class="table-actions">
          <el-button type="warning" @click="loadOverdueRecords">
            <el-icon><Warning /></el-icon>
            查看逾期记录
          </el-button>
        </div>
      </div>
      
      <el-table
        v-loading="loading"
        :data="borrowRecords"
        stripe
      >
        <el-table-column prop="username" label="用户" width="120" />
        
        <el-table-column prop="bookTitle" label="图书" min-width="200" />
        
        <el-table-column prop="bookAuthor" label="作者" width="120" />
        
        <el-table-column prop="borrowDate" label="借阅日期" width="120">
          <template #default="{ row }">
            {{ formatDate(row.borrowDate) }}
          </template>
        </el-table-column>
        
        <el-table-column prop="dueDate" label="应还日期" width="120">
          <template #default="{ row }">
            <span :class="{ 'text-danger': isOverdue(row.dueDate, row.status) }">
              {{ formatDate(row.dueDate) }}
            </span>
          </template>
        </el-table-column>
        
        <el-table-column prop="returnDate" label="归还日期" width="120">
          <template #default="{ row }">
            {{ row.returnDate ? formatDate(row.returnDate) : '-' }}
          </template>
        </el-table-column>
        
        <el-table-column prop="renewCount" label="续借次数" width="100" align="center" />
        
        <el-table-column prop="status" label="状态" width="100">
          <template #default="{ row }">
            <el-tag
              :type="getStatusType(row.status)"
              size="small"
            >
              {{ getStatusText(row.status) }}
            </el-tag>
          </template>
        </el-table-column>
        
        <el-table-column prop="fine" label="罚金" width="80">
          <template #default="{ row }">
            <span v-if="row.fine > 0" class="text-danger">
              ¥{{ row.fine.toFixed(2) }}
            </span>
            <span v-else>-</span>
          </template>
        </el-table-column>
        
        <el-table-column label="操作" width="150" fixed="right">
          <template #default="{ row }">
            <el-button
              v-if="row.status === 'BORROWED'"
              type="success"
              size="small"
              @click="handleReturn(row)"
            >
              归还
            </el-button>
            
            <el-button
              v-if="row.status === 'BORROWED' && row.renewCount < 2"
              type="primary"
              size="small"
              @click="handleRenew(row)"
            >
              续借
            </el-button>
          </template>
        </el-table-column>
      </el-table>
      
      <!-- 分页 -->
      <div class="pagination">
        <el-pagination
          v-model:current-page="pagination.current"
          v-model:page-size="pagination.size"
          :total="pagination.total"
          :page-sizes="[10, 20, 50, 100]"
          layout="total, sizes, prev, pager, next, jumper"
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
        />
      </div>
    </div>
  </div>
</template>

<script setup>
import { ref, reactive, onMounted } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import { getBorrowList, returnBook, renewBook, getBorrowStats, getOverdueRecords } from '@/api/borrow'
import {
  Search,
  Refresh,
  Warning
} from '@element-plus/icons-vue'

// 加载状态
const loading = ref(false)

// 搜索表单
const searchForm = reactive({
  keyword: '',
  status: '',
  dateRange: []
})

// 分页信息
const pagination = reactive({
  current: 1,
  size: 10,
  total: 0
})

// 数据
const borrowRecords = ref([])
const stats = ref({})

// 格式化日期
const formatDate = (date) => {
  if (!date) return '-'
  return new Date(date).toLocaleDateString()
}

// 判断是否逾期
const isOverdue = (dueDate, status) => {
  if (status !== 'BORROWED') return false
  return new Date(dueDate) < new Date()
}

// 获取状态类型
const getStatusType = (status) => {
  switch (status) {
    case 'BORROWED':
      return 'primary'
    case 'RETURNED':
      return 'success'
    case 'OVERDUE':
      return 'danger'
    default:
      return 'info'
  }
}

// 获取状态文本
const getStatusText = (status) => {
  switch (status) {
    case 'BORROWED':
      return '借阅中'
    case 'RETURNED':
      return '已归还'
    case 'OVERDUE':
      return '已逾期'
    default:
      return '未知'
  }
}

// 加载借阅记录
const loadBorrowRecords = async () => {
  try {
    loading.value = true
    
    const params = {
      current: pagination.current,
      size: pagination.size,
      keyword: searchForm.keyword,
      status: searchForm.status
    }
    
    // 处理日期范围
    if (searchForm.dateRange && searchForm.dateRange.length === 2) {
      params.startDate = searchForm.dateRange[0]
      params.endDate = searchForm.dateRange[1]
    }
    
    const response = await getBorrowList(params)
    const { records, total } = response.data
    
    borrowRecords.value = records
    pagination.total = total
  } catch (error) {
    console.error('加载借阅记录失败:', error)
  } finally {
    loading.value = false
  }
}

// 加载统计数据
const loadStats = async () => {
  try {
    const response = await getBorrowStats()
    stats.value = response.data
  } catch (error) {
    console.error('加载统计数据失败:', error)
  }
}

// 加载逾期记录
const loadOverdueRecords = async () => {
  try {
    searchForm.status = 'OVERDUE'
    searchForm.keyword = ''
    searchForm.dateRange = []
    pagination.current = 1
    await loadBorrowRecords()
    ElMessage.info('已筛选出逾期记录')
  } catch (error) {
    console.error('加载逾期记录失败:', error)
  }
}

// 搜索
const handleSearch = () => {
  pagination.current = 1
  loadBorrowRecords()
}

// 重置
const handleReset = () => {
  Object.assign(searchForm, {
    keyword: '',
    status: '',
    dateRange: []
  })
  pagination.current = 1
  loadBorrowRecords()
}

// 分页大小改变
const handleSizeChange = (size) => {
  pagination.size = size
  pagination.current = 1
  loadBorrowRecords()
}

// 当前页改变
const handleCurrentChange = (current) => {
  pagination.current = current
  loadBorrowRecords()
}

// 归还图书
const handleReturn = async (record) => {
  try {
    await ElMessageBox.confirm(
      `确定要归还图书「${record.bookTitle}」吗？`,
      '确认归还',
      {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }
    )
    
    await returnBook(record.id)
    ElMessage.success('归还成功')
    loadBorrowRecords()
    loadStats()
  } catch (error) {
    if (error !== 'cancel') {
      console.error('归还失败:', error)
    }
  }
}

// 续借图书
const handleRenew = async (record) => {
  try {
    await ElMessageBox.confirm(
      `确定要续借图书「${record.bookTitle}」吗？\n续借后到期日期将延长30天。`,
      '确认续借',
      {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'info'
      }
    )
    
    await renewBook(record.id)
    ElMessage.success('续借成功')
    loadBorrowRecords()
  } catch (error) {
    if (error !== 'cancel') {
      console.error('续借失败:', error)
    }
  }
}

// 初始化
onMounted(() => {
  loadBorrowRecords()
  loadStats()
})
</script>

<style scoped>
.borrow-list {
  max-width: 1400px;
  margin: 0 auto;
}

.stats-row {
  display: grid;
  grid-template-columns: repeat(auto-fit, minmax(200px, 1fr));
  gap: 16px;
  margin-bottom: 20px;
}

.stat-card {
  background: #fff;
  border-radius: 8px;
  padding: 20px;
  text-align: center;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);
}

.stat-value {
  font-size: 24px;
  font-weight: 600;
  color: #333;
  margin-bottom: 8px;
}

.stat-label {
  font-size: 14px;
  color: #666;
}

.text-danger {
  color: #f56c6c;
}

.pagination {
  margin-top: 20px;
  text-align: right;
}

@media (max-width: 768px) {
  .search-form {
    flex-direction: column;
  }
  
  .search-item {
    min-width: auto;
  }
  
  .table-header {
    flex-direction: column;
    gap: 16px;
    align-items: stretch;
  }
  
  .stats-row {
    grid-template-columns: repeat(auto-fit, minmax(150px, 1fr));
  }
}
</style>